<template>
	  <eui-base-card v-for="item1 in PropsData.data" :key="item1.c_ccode" :title="item1.c_cname" titleLine>
	<view class="flex-start-center item-box" style="background-color: #FFFFFF;" v-for="item in item1.lstDoc"
		:key="item.c_guid" @click="handleFileAction(item)">

		<view class="left">
			<!-- TODO 未读已读 -->
			<span class="point" v-show="item==1"></span>

			<image :src="'../../../static/img/knowledge/' +item.c_docimg_url" mode="scaleToFill" class="image" />
		</view>
		<view class="right flex-column-between" style="background-color: RGBA(255,255,255,0);">
			<view class="text-ellipsis sub_title flex_1">{{item.c_title}}</view>
			<view class="flex-start-center">
				<eui-tag :text="item.c_cname" plain plainFill :bgColor="themeBgColor" :borderColor="themeBgColor" :color="themeColor"></eui-tag>
				<view class="text-ellipsis sub_des">{{ item.c_mk_dt }}</view>
				<view class="text-ellipsis sub_des">{{ item.c_mk_username }}</view>
			</view>
		</view>
		<view class="flex-column-between" style="align-items: center;height: 44px;">
			<view v-if="item.c_type=='文件'" class="iconfont icon-xiazai" style="font-size: 20px;" :style="{color:themeStore.theme=='theme-blue'?'rgba(2, 183, 230, 1)':'#FF6430'}"></view>
			<view v-if="item.c_type=='在线编辑' || item.c_type=='地址链接'" class="iconfont icon-chakan" :style="{color:themeStore.theme=='theme-blue'?'rgba(2, 183, 230, 1)':'#FF6430'}"
				style="font-size: 23px;"></view>
			<view v-if="item.c_type=='文件'" class="text-ellipsis sub_des" style="font-size: 18rpx;">下载量:
				{{ item.c_download_count }}
			</view>
			<view v-if="item.c_type=='在线编辑' || item.c_type=='地址链接'" class="text-ellipsis sub_des"
				style="font-size: 18rpx;">下载量: {{ item.c_download_count }}</view>
		</view>
	</view>
     </eui-base-card>
	<view v-if="PropsData.data.length == 0" class="no-data flex flex-direction-column">
		<image src="@/static/img/no_data.png" mode="aspectFit" class="image" />
		<view class="color-888 font-size-28">暂无数据</view>
	</view>

</template>

<script setup lang="ts">
	import service from '@/common/service';
	import { ref, defineProps } from 'vue';
	import { useLoginStore } from '@/store/modules/useLoginStore';
	import { useMainStore } from '@/store/modules/store';
	import { useThemeStore } from '@/store/themeStore';
	import { storeToRefs } from 'pinia';
	const themeStore = useThemeStore(); // 主题
	const { theme } = storeToRefs(themeStore);
	const themeBgColor = ref(themeStore.theme == 'theme-blue' ? 'rgba(224, 239, 255, 0.5)' : 'rgba(255, 239, 224, 0.5)')
	const themeColor = ref(themeStore.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')
	/**
	 *  知识门户
	 */
	interface File {
		c_docimg_url : string,
		c_title : string,
		c_mk_dt : string,
		c_mk_username : string,
		c_download_count : number,
		c_cname : string,
		c_guid : string,
		c_link : string,
		c_type ?: string;
		c_file_name : string;
		filePath : string;
		c_id : string;
		[key : string] : any;
	}
	const LoginStore = useLoginStore();
	const mainStore = useMainStore();
	const PropsData = defineProps<{ data : Array<File> }>();


	// const downloadFile = (file : File) => {
	// 	console.log(file);

	// 	uni.downloadFile({
	// 		url: file.filePath, // PDF文件的网络地址
	// 		//url: 'http://60.208.83.246:9007/File/DownLoadPdfFile/834e064d-309d-4c61-a71c-137a0e0c35d0' ,
	// 		success: function (res) {
	// 			if (res.statusCode === 200) {
	// 				uni.saveFile({
	// 					tempFilePath: res.tempFilePath,
	// 					success: function (saveRes) {
	// 						UpdateDownloadCount(file.c_id)
	// 						console.log('文件保存成功，路径为：' + saveRes.savedFilePath);
	// 						uni.showToast({
	// 							title: '保存成功',
	// 							icon: 'success',
	// 							mask: true
	// 						})
	// 						setTimeout(() => {
	// 							let fileExtension = file.c_file_name.substring(file.c_file_name.lastIndexOf('.') + 1);
	// 							console.log('文件路径:'+saveRes.savedFilePath);
	// 							uni.openDocument({
	// 								filePath: saveRes.savedFilePath, // 文件路径
	// 								fileType: fileExtension, // 文件类型
	// 								showMenu: true,
	// 								success: function () {
	// 									console.log('文件预览成功');
	// 								},
	// 								fail: function (err) {
	// 									console.error('文件预览失败：', err);
	// 								}
	// 							});

	// 						}, 2000);
	// 					},
	// 					fail: function (err) {
	// 						console.error('文件保存失败：', err);
	// 						uni.showToast({
	// 							title: '文件保存失败：' + err,
	// 							icon: 'error',
	// 							mask: true
	// 						})
	// 					}
	// 				});
	// 			} else {
	// 				service.enjoyShowToast('下载文件失败，状态码：' + res.statusCode)
	// 				console.error('下载文件失败，状态码：' + res.statusCode);
	// 			}
	// 		},
	// 		fail: function (err) {
	// 			service.enjoyShowToast('下载文件请求失败：' + err)
	// 		}
	// 	});
	// }
	const handleFileAction = (file : File) => {
		switch (file.c_type) {
			case '文件':
				uni.showModal({
					title: '提示',
					content: '确定要下载该文件吗?',
					success: function (res) {
						if (res.confirm) {
							let request = {
								url: LoginStore.EnjoyMain,
								data: {
									UniqueKey: "管易通40知识中心",
									MethodName: "GetDownloadUrl",
									ObjectData: {
										sUserNo: mainStore.loginInfo.sUser,
										sGuid: file.c_guid,
										sFileName: file.c_file_name
									}
								},
							};
							console.log('入参:' + JSON.stringify(request));
							service.request(request, (res : any) => {
								
								console.log('出参:' + JSON.stringify(res.data));
								if (res && res.data && !res.data.HasException) {
									UpdateDownloadCount(file.c_id);
									console.log('plus.os.name:'+plus.os.name);
									var url = `${LoginStore.EnjoyMain.replace('/Enjoy/Service', '/DownloadTempFile/')}${mainStore.loginInfo.sUser}` + '/' + encodeURI(file.c_file_name);
									if (plus.os.name != "iOS") {
										plus.runtime.openURL(url);
									} else {
										console.log('fileName:'+file.c_file_name)
										let options = {
											filename: '_downloads/' + file.c_file_name,
											method: 'GET',
										};
										plus.io.resolveLocalFileSystemURL(options.filename,
											function (entry) {
												FileExistsCallback(entry, options, file.c_file_name,
													url);
											},
											function (e) {
												FileNotExistsCallback(e, options, file.c_file_name,
													url);
											}
										);
									}
								} else {
									service.enjoyShowToast(res.data.Exception.Message)
								}

								service.enjoyHideLoading();
							}, () => {
								service.enjoyHideLoading();
								console.log('失败')
							});
					}}
				});
				break;
			case '在线编辑':
				console.log('FileData:' + JSON.stringify(file));
				UpdateReadCount(file.c_id);
				uni.navigateTo({
					url: './KnowledgeRichText?data=' + JSON.stringify(file)
				});

				break;
			case '地址链接':
				// 处理地址链接逻辑
				console.log("link:" + file.c_link);
				var lk = file.c_link;
				UpdateReadCount(file.c_id);
				if (lk.substring(0, 4) == 'www.') {
					lk = 'http://' + lk;
				}
				//iframe打开安全链接有安全限制，直接用浏览器打开
				if (lk.substr(0, 5) == 'https') {
					plus.runtime.openURL(lk);
				} else {
					uni.navigateTo({
						url: './KnowledgeRichText?data=' + JSON.stringify(file)
					});
				}
				break;
			default:
				console.warn('未知的文件类型:', file.c_type);
		}
	}
//文件已存在
	const FileExistsCallback = (entry, options, filename, guid) => {
		uni.showModal({
			title: '提示',
			content: '选择的文件已下载过,是否直接打开',
			success: function (res) {
				if (res.confirm) {
					// 直接打开
					plus.runtime.openFile(options.filename, function (e) {
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: "无法打开此文件：" + e.emssage,
							mask: true,
						});
					});
				} else if (res.cancel) { }
			}
		});
	}
	//文件不存在回调函数
	const FileNotExistsCallback = (e, options, filename, c_url) => {
		downLoadFile(options, filename, c_url);
	}
	const downLoadFile = (option, filename, c_url) => {
			let i = 0;
			let updateWatting = plus.nativeUI.showWaiting("正在准备下载文件...");
			let downUrl = c_url;
			let dtask = plus.downloader.createDownload(c_url, option);
			dtask.addEventListener("statechanged", function (task, status) {
				if (!dtask) {
					return;
				}
				switch (task.state) {
					case 1: // 开始
						updateWatting.setTitle("开始下载...");
						break;
					case 2: // 已连接到服务器
						updateWatting.setTitle("链接到服务器...");
						break;
					case 3: // 已接收到数据
						updateWatting.setTitle("已下载:" + task.downloadedSize + "/" + task.totalSize);
						break;
					case 4: // 下载完成
						updateWatting.close();
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: '下载完成!',
							mask: true,
						});
						console.log('开始打开:'+option.filename);
						plus.runtime.openFile(option.filename, function (e) {
							uni.showToast({
								duration: 3500,
								icon: 'none',
								title: "无法打开此文件：" + e.emssage,
								mask: true,
							});
						});
						break;
				}
			});
			dtask.start();
		}
	const UpdateReadCount = (bId) => {
		let request = {
			url: LoginStore.EnjoyMain,
			data: {
				UniqueKey: "管易通40知识中心",
				MethodName: "UpdateReadCount",
				ObjectData: bId,
				UserNo: mainStore.loginInfo.sUser
			},
		};
		service.request(request, (res : any) => {
			if (res && res.data && !res.data.HasException) {

			} else {
				service.enjoyShowToast(res.data.Exception.Message)
			}

			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
			console.log('失败')
		});
	}
	const UpdateDownloadCount = (bId) => {
		let request = {
			url: LoginStore.EnjoyMain,
			data: {
				UniqueKey: "管易通40知识中心",
				MethodName: "UpdateDownloadCount",
				ObjectData: bId,
				UserNo: mainStore.loginInfo.sUser
			},
		};
		service.request(request, (res : any) => {
			if (res && res.data && !res.data.HasException) {

			} else {
				service.enjoyShowToast(res.data.Exception.Message)
			}

			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
			console.log('失败')
		});
	}
</script>

<style lang="scss" scoped>
	.item-box {
		padding: 8px;
		margin-bottom: 8px;
		border-radius: 8px;
	}

	.left {
		position: relative;
		width: 44px;
		height: 44px;

		.point {
			position: absolute;
			top: 2px;
			right: 1px;
		}

		.image {
			width: 100%;
			height: 100%;
		}
	}

	.right {
		flex: 1;
		width: 0;
		height: 44px;
		margin-left: 10px;
	}

	.sub_des {
		margin-right: 8px;
	}

	.flex-direction-column {
		flex-direction: column !important;
	}

	.color-888 {
		color: rgba(136, 136, 136, 1);
	}

	.font-size-28 {
		font-size: 28rpx;
	}
</style>